package com.vip.jwt.config;

import com.vip.jwt.common.exception.ExceptionEnum;
import com.vip.jwt.common.exception.MyException;
import com.vip.jwt.common.utils.JwtUtil;
import com.vip.jwt.entity.Role;
import com.vip.jwt.entity.User;
import com.vip.jwt.service.RolePermissionService;
import com.vip.jwt.service.UserRoleService;
import com.vip.jwt.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private HttpServletRequest request;

    @Resource
    private UserService userService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePermissionService rolePermissionService;

    /*
     * 多重写一个support
     * 标识这个Realm是专门用来验证JwtToken
     * 不负责验证其他的token（UsernamePasswordToken）
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = principalCollection.toString();
        String username = JwtUtil.getUsername(token);
        User user = userService.findByUsername(username);
        String userId = user.getId();
        List<Role> roles = userRoleService.findByUserId(userId);
        List<String> roleStrs = roles.stream()
                .map(Role::getCode)
                .collect(Collectors.toList());
        List<String> allPermissionStrs = new ArrayList<>();
        for(int i=0;i<roles.size();i++){
            Role role = roles.get(i);
            String roleId = role.getId();
            List<String> strings = rolePermissionService.findByRoleId(roleId);
            allPermissionStrs.addAll(strings);
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roleStrs);
        simpleAuthorizationInfo.addStringPermissions(allPermissionStrs);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String)authenticationToken.getPrincipal();
        String username = JwtUtil.getUsername(token);
        if(null == username){
            //todo 抛异常 token验证错误
            throw new MyException(ExceptionEnum.TOKEN_INVALID);
        }
        //todo 根据用户名在数据库查找用户，如果用户为空，则用户不存在
        String password = "456";
        boolean verify = JwtUtil.verify(request,username,password);
        if(!verify){
            //todo 用户名或者密码错误
        }
        return new SimpleAuthenticationInfo(token,token,getName());
    }

}
